<?php

namespace api\modules\backend\models;

use Yii;
use \yii\db\ActiveRecord;

/**
 * Member Level Model
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class MemberLevel extends ActiveRecord
{
    public $_filterQuery;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%member_level}}';
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['member_level_id'];
    }

    /**
     * Define rules for validation
     */
    public function rules()
    {
        return [
            [['number', 'member_id', 'level', 'payment_amount'], 'required'],
            [['number'], 'unique'],
            [['number', 'level', 'payment_amount'], 'validatePositive'],
            [['number', 'payment_amount'], 'number'],
            [['status'], 'in', 'range' => [0, 1, 2]],
            [['level'], 'in', 'range' => [1, 2]]
        ];
    }

    public function validatePositive($attribute, $params)
    {
        return true;
    }

    public function filterQuery($getRawSql, $status, $expireTime, $memberId = null)
    {
        $this->_filterQuery = self::find()->where(['status' => $status])->andWhere(['>=', 'expire_time', $expireTime]);

        if ($memberId) {
            $this->_filterQuery->andWhere(['member_id' => $memberId]);
        }

        return $getRawSql ? $this->_filterQuery->createCommand()->getRawSql() : $this->_filterQuery;
    }
}
